# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# (C) 2012 Remek Zajac
#!/usr/bin/python

import cairo
import threading
import gobject

#local modules
import pyGpxOSMTiles
import pyOSM2SQL
import pyGeometry
import pyConfig


class OSMTileRendererThread(threading.Thread):
    def __init__(self, parent, tile, callback=None):
        super(OSMTileRendererThread, self).__init__()
        self.tile = tile
        self.callback = callback
        self.tile.createCacheFolder()
        self.drawingToolkit = parent.drawingToolkit()
        self.config = parent.config()
        print ">>Start rendering: ",self.tile.getLocalFileName()

    def run(self):
        width = pyGpxOSMTiles.OSMTilesReferenceMap.ETileDimensions[0]
        height = pyGpxOSMTiles.OSMTilesReferenceMap.ETileDimensions[1]
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
        cr = cairo.Context(surface)
        waynodescursor = pyOSM2SQL.WayNodes.Instance().cursor()
        region = pyGeometry.GeoRegion((0,0,width, height))        
        waynodescursor.wayNodesForRegion(self.tile.region())
        wayid = None
        roadDrawingTool = None
        try:
            while 1:
                waynode = waynodescursor.fetchone()
                if wayid != waynode.wayid:
                    way = self.config.ways.way(waynode.attributes["highway"], self.tile.zoom)
                    if way:
                        roadDrawingTool = self.drawingToolkit.roadTool()
                        roadDrawingTool.init(cr, way, region)
                    else:
                        roadDrawingTool = None
                    wayid = waynode.wayid
                if roadDrawingTool:
                    roadDrawingTool.draw(self.tile.latlon2pix(waynode.latlon))
        except EOFError:
            print "EOF"
        print "<<Done rendering: ",self.tile.getLocalFileName()
        surface.write_to_png(self.tile.getLocalFileName())
        if self.callback:
            gobject.idle_add(self.callback, self.tile)
        

#************************************************************************
# A generation and cache engine for locally rendered OSM tile files
#************************************************************************       
class OSMLocalTileRenderingEngine(pyGpxOSMTiles.TilesGeneratingEngineBase):
    def __init__(self, parent):
        super(OSMLocalTileRenderingEngine,self).__init__()
        self.cache = pyGpxOSMTiles.TileCache( r'./.localCache/locallyRenderedTiles/' )
        self.cache.trimFilesOlderThan(parent.config().lastUpdated())
        self.parent = parent

    def getTile(self, x, y, zoom, callback = None):
        tile = pyGpxOSMTiles.CachedTile(x,y,zoom, self.cache)
        if tile.isCached():
            return tile
        threadedDownload = OSMTileRendererThread(self.parent, tile, callback )
        return self.getTileThreaded(threadedDownload)
    
        

